package com.tt.vtg.scenario.http.server;

import com.tt.vtg.scenario.http.decoder.HttpJsonRequestDecoder;
import com.tt.vtg.scenario.http.encoder.HttpJsonResponseEncoder;
import com.tt.vtg.scenario.http.handler.HttpJsonServerHandler;
import com.tt.vtg.scenario.http.pojo.RequestEntity;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;

import java.net.InetSocketAddress;

public class HttpServerBootStrap {
    public void start(final int port) throws Exception{
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try{
            ServerBootstrap boot = new ServerBootstrap();
            boot.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch)
                                throws Exception {

                            /*
                            *           ByteBuf -> HttpRequestDecoder # HttpObjectAggregator -> FullHttpRequest -> HttpJsonRequestDecoder
                            *           HttpJsonResponseEncoder -> HttpResponseEncoder
                            * */
                            ch.pipeline().addLast("http-decoder", new HttpRequestDecoder());
                            ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(512*1024));
                            ch.pipeline().addLast("http-json-decoder", new HttpJsonRequestDecoder<>(RequestEntity.class));

                            // handler response
                            ch.pipeline().addLast("http-encoder", new HttpResponseEncoder());
                            ch.pipeline().addLast("http-json-encoder", new HttpJsonResponseEncoder());

                            //handler HttpJsonRequest
                            ch.pipeline().addLast("http-json-handler", new HttpJsonServerHandler());
                        }
                    });
            ChannelFuture future = boot.bind(new InetSocketAddress(port)).sync();
            System.out.println("Server start @ : " + "http://localhost:" + port);
            future.channel().closeFuture().sync();

        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception{
        new HttpServerBootStrap().start(9527);
    }
}
